/* eslint-disable */
<template>
  <el-form
    ref="formRef"
    :model="form"
    :rules="rules"
    label-width="100px"
    class="change-password-form"
  >
    <!-- 步骤1：输入邮箱 -->
    <div v-if="currentStep === 1">
      <el-form-item label="邮箱地址" prop="email">
        <el-input
          v-model="form.email"
          placeholder="请输入您的邮箱地址"
          :disabled="true"
        />
        <div class="field-tip">系统将向此邮箱发送验证码</div>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="sendCaptcha" :loading="sendingCaptcha">
          发送验证码
        </el-button>
      </el-form-item>
    </div>
    <!-- 步骤2：输入验证码 -->
    <div v-if="currentStep === 2">
      <el-form-item label="验证码" prop="captcha">
        <el-input
          v-model="form.captcha"
          placeholder="请输入6位数字验证码"
          maxlength="6"
          show-word-limit
        />
        <div class="field-tip">
          验证码已发送到 {{ form.email }}
          <el-button link @click="sendCaptcha" :disabled="countdown > 0">
            {{ countdown > 0 ? `${countdown}s后重发` : '重新发送' }}
          </el-button>
        </div>
      </el-form-item>
      <el-form-item>
        <el-button @click="currentStep = 1">上一步</el-button>
        <el-button type="primary" @click="verifyCaptcha" :loading="verifying">
          验证
        </el-button>
      </el-form-item>
    </div>
    <!-- 步骤3：输入新密码 -->
    <div v-if="currentStep === 3">
      <el-form-item label="原密码" prop="oldPassword">
        <el-input
          v-model="form.oldPassword"
          type="password"
          placeholder="请输入原密码"
          show-password
        />
      </el-form-item>
      <el-form-item label="新密码" prop="newPassword">
        <el-input
          v-model="form.newPassword"
          type="password"
          placeholder="请输入新密码"
          show-password
        />
      </el-form-item>
      <el-form-item label="确认密码" prop="confirmPassword">
        <el-input
          v-model="form.confirmPassword"
          type="password"
          placeholder="请再次输入新密码"
          show-password
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="currentStep = 2">上一步</el-button>
        <el-button type="primary" @click="submitChange" :loading="submitting">
          确认修改
        </el-button>
      </el-form-item>
    </div>
  </el-form>
  <!-- 步骤指示器 -->
  <div class="step-indicator">
    <div class="step-item" :class="{ active: currentStep >= 1, completed: currentStep > 1 }">
      <div class="step-number">1</div>
      <div class="step-text">验证邮箱</div>
    </div>
    <div class="step-line" :class="{ active: currentStep > 1 }"></div>
    <div class="step-item" :class="{ active: currentStep >= 2, completed: currentStep > 2 }">
      <div class="step-number">2</div>
      <div class="step-text">输入验证码</div>
    </div>
    <div class="step-line" :class="{ active: currentStep > 2 }"></div>
    <div class="step-item" :class="{ active: currentStep >= 3 }">
      <div class="step-number">3</div>
      <div class="step-text">修改密码</div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useStore } from 'vuex'
import { ElMessage } from 'element-plus'
import { sendChangePasswordCaptcha, changePassword } from '@/api/user'

// eslint-disable-next-line no-undef
const emit = defineEmits(['success'])
const store = useStore()
const formRef = ref(null)
const currentStep = ref(1)
const sendingCaptcha = ref(false)
const verifying = ref(false)
const submitting = ref(false)
const countdown = ref(0)

// 表单数据
const form = reactive({
  email: '',
  captcha: '',
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 表单验证规则
const rules = {
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '邮箱格式不正确', trigger: 'blur' }
  ],
  captcha: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { pattern: /^\d{6}$/, message: '验证码为6位数字', trigger: 'blur' }
  ],
  oldPassword: [
    { required: true, message: '请输入原密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    { validator: (rule, value, callback) => {
        if (value !== form.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      }, trigger: 'blur' }
  ]
}

// 初始化表单
const initForm = () => {
  const user = store.state.user.userInfo || store.state.user
  form.email = user.email || ''
  form.captcha = ''
  form.oldPassword = ''
  form.newPassword = ''
  form.confirmPassword = ''
  currentStep.value = 1
  countdown.value = 0
}

// 每次进入组件时初始化
initForm()

// 发送验证码
const sendCaptcha = async () => {
  try {
    sendingCaptcha.value = true
    const res = await sendChangePasswordCaptcha({ email: form.email })
    if (res.code === 200) {
      ElMessage.success('验证码已发送到邮箱')
      currentStep.value = 2
      startCountdown()
    } else {
      ElMessage.error(res.message || '发送失败')
    }
  } catch (error) {
    console.error('发送验证码失败:', error)
    ElMessage.error('发送验证码失败')
  } finally {
    sendingCaptcha.value = false
  }
}

// 开始倒计时
const startCountdown = () => {
  countdown.value = 60
  const timer = setInterval(() => {
    countdown.value--
    if (countdown.value <= 0) {
      clearInterval(timer)
    }
  }, 1000)
}

// 验证验证码
const verifyCaptcha = async () => {
  try {
    await formRef.value.validateField('captcha')
    verifying.value = true
    // 这里只是验证验证码格式，实际验证在提交时进行
    currentStep.value = 3
    ElMessage.success('验证码格式正确，请继续')
  } catch (error) {
    console.error('验证失败:', error)
  } finally {
    verifying.value = false
  }
}

// 提交修改
const submitChange = async () => {
  try {
    await formRef.value.validate()
    submitting.value = true
    const res = await changePassword({
      oldPassword: form.oldPassword,
      newPassword: form.newPassword,
      email: form.email,
      captcha: form.captcha
    })
    if (res.code === 200) {
      ElMessage.success('密码修改成功')
      emit('success')
    } else {
      ElMessage.error(res.message || '修改失败')
    }
  } catch (error) {
    console.error('修改密码失败:', error)
    ElMessage.error('修改密码失败')
  } finally {
    submitting.value = false
  }
}
</script>

<style scoped>
.change-password-form {
  margin-bottom: 20px;
}

.field-tip {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
}

.step-indicator {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 30px;
  padding: 20px 0;
  border-top: 1px solid #eee;
}

.step-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  position: relative;
}

.step-number {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  background: #f0f0f0;
  color: #999;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  margin-bottom: 8px;
  transition: all 0.3s;
}

.step-item.active .step-number {
  background: #409eff;
  color: white;
}

.step-item.completed .step-number {
  background: #67c23a;
  color: white;
}

.step-text {
  font-size: 12px;
  color: #999;
  text-align: center;
}

.step-item.active .step-text {
  color: #409eff;
}

.step-item.completed .step-text {
  color: #67c23a;
}

.step-line {
  width: 60px;
  height: 2px;
  background: #f0f0f0;
  margin: 0 10px;
  margin-bottom: 20px;
  transition: all 0.3s;
}

.step-line.active {
  background: #67c23a;
}

.el-form-item {
  margin-bottom: 20px;
}

.el-button {
  margin-right: 10px;
}
</style> 